package orchestration.android.execution;

import orchestration.android.OrchestratorApp;
import orchestration.android.R;
import orchestration.businessprocess.execution.IBPExecutionContainter;
import orchestration.businessprocess.model.BusinessProcessModel;
import orchestration.conditions.IConditionEvaluator;
import orchestration.conditions.jexlImpl.JexlAdapter;
import orchestration.persistence.BusinessProcessModelDAO;
import orchestration.persistence.BusinessProcessModelDAOImpl;
import orchestration.persistence.PropertyDAO;
import orchestration.persistence.OrchestratorAuthority.AndroidProcess;
import orchestration.persistence.sqlite.OrchestratorDatabaseHelper;
import orchestration.persistence.sqlite.PropertyDAOImpl;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.net.Uri;

/**
 * @author  <a href="mailto:car.ferrarini@gmail.com">Carlo Ferrarini</a>
 */
public abstract class AbstractBPEService extends Service implements IBPExecutionContainter {

	/**
	 * @uml.property  name="pDao"
	 * @uml.associationEnd  
	 */
	private PropertyDAO pDao;
	/**
	 * @uml.property  name="cEval"
	 * @uml.associationEnd  
	 */
	private IConditionEvaluator cEval;
	/**
	 * @uml.property  name="bpmDAO"
	 * @uml.associationEnd  
	 */
	private BusinessProcessModelDAO bpmDAO;
	
	@Override
	public BusinessProcessModel getBusinessProcessModel(long procId) {
		Uri procUri=Uri.withAppendedPath(AndroidProcess.CONTENT_URI, ""+procId);
		return getCache().getBpm(procUri);
	}

	@Override
	public IConditionEvaluator getConditionEvaluator() {
		if(cEval==null)
			cEval= new JexlAdapter();
		return cEval;
	}

	@Override
	public PropertyDAO getPropertyDAO() {
		if(pDao==null){
			pDao= new PropertyDAOImpl(new OrchestratorDatabaseHelper(this));
		}
		return pDao;
	}
	
	public BusinessProcessModelDAO getBusinessProcessModelDAO() {
		if(bpmDAO==null){
			bpmDAO= new BusinessProcessModelDAOImpl();
		}
		return bpmDAO;
	}
	public IOrchestrationCache getCache(){
		return (IOrchestrationCache)getApplication();
	}
	public void handleException(Exception e){
		e.printStackTrace();
		NotificationManager nm= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.error_icon,"Exception",System.currentTimeMillis());
		notification.setLatestEventInfo(this, "Exception in Business Process Service", e.getMessage(), PendingIntent.getActivity(this, 0, null, 0));
		nm.notify(((OrchestratorApp)getApplication()).newNotificationId(), notification);
	}
}











